﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using ShoppeWCFService.dbShoppeTableAdapters;

namespace ShoppeWCFService
{
    
    public class ShoppeService : IShoppeService
    {
        /// <summary>
        /// Returns the products, whith choosen category you want to see
        /// </summary>
        /// <param name="targetCategory">The name of the category</param>
        /// <returns>All products with target category</returns>
        public DataSet getTargetCategory(String targetCategory){
            fn_targetCategoryTableAdapter adapter = new fn_targetCategoryTableAdapter();
            DataSet result = new DataSet();
            try{
                result = tableToSet(adapter.GetData(targetCategory));
            }
            finally{
                adapter.Connection.Close();
            }
            return result;
        }

        /// <summary>
        /// Get the product of target ID
        /// </summary>
        /// <param name="targetId">Choosen Id</param>
        /// <returns>The product in form of a DataSet</returns>
        public DataSet getTargetProduct(int targetId) {
            totalproductTableAdapter adapter = new totalproductTableAdapter();
            DataSet result = new DataSet();
            try {
                result = tableToSet(adapter.GetDataById(targetId));
            }
            finally {
                adapter.Connection.Close();
            }
            return result;
        }

        /// <summary>
        /// Returns a collection of strings with all the categorys in the databas
        /// Main use is to have easy access, when filling menus and inputs in the pages
        /// </summary>
        /// <returns>Collection of the names of all categorys in database</returns>
        public List<String> getAllCategorys(){
            fn_getMenuItemsTableAdapter adapter = new fn_getMenuItemsTableAdapter();
            List<String> result = new List<string>();

            try
            {
                foreach (DataRow row in adapter.GetData())
                {
                    result.Add(row["name"].ToString());
                }
            }
            finally {
                adapter.Connection.Close();
            }

            return result;
        }

        /// <summary>
        /// Returns a DataSet contaning all categorys and there corresponding ID 
        /// </summary>
        /// <returns>All categorys in database</returns>
        public DataSet getCategorys() {
            categoryTableAdapter adapter = new categoryTableAdapter();
            DataSet result = new DataSet();
            try
            {
                result = tableToSet(adapter.GetData());
            }
            finally { 
                adapter.Connection.Close();
            }
            return result;
        }

        /// <summary>
        /// Returns a DataSet contaning all imageURL's and there corresponding ID 
        /// </summary>
        /// <returns>All images in database</returns>
        public DataSet getAllImages() {
            productimageTableAdapter adapter = new productimageTableAdapter();
            DataSet result = new DataSet();
            try
            {
                result = tableToSet(adapter.GetData());
            }
            finally { adapter.Connection.Close(); }
            return result;
        }

        /// <summary>
        /// Insert a new product in the database
        /// </summary>
        /// <param name="name">Product name</param>
        /// <param name="imageURL">Target imageURL ID</param>
        /// <param name="description">Text describing how the product works, behavie, looks etc.</param>
        /// <param name="stockStatus">How many items of the product we initially have in stock</param>
        /// <param name="category">What type of a product</param>
        /// <param name="price">The cost of the product</param>
        public void addNewProduct(String name, String imageURL, String description, int stockStatus, String category, int price) {
            productTableAdapter adapter = new productTableAdapter();
            try {
               adapter.addProduct(
               name,
               Int16.Parse(imageURL),
               description,
               stockStatus,
               Int16.Parse(category),
               price);
            }
            finally { adapter.Connection.Close(); }
        }

        /// <summary>
        /// Returns the products where the name contains the parameter
        /// </summary>
        /// <param name="sWord">Part of a product name</param>
        /// <returns>All products in a DataSet that contains searchword</returns>
        public DataSet search(String sWord) {
            if (sWord == null) { sWord = ""; }
            fn_searchTableAdapter search = new fn_searchTableAdapter();
            return tableToSet(search.GetData(sWord));
        }

        /// <summary>
        /// Get all products in database
        /// </summary>
        /// <returns>All products in a DataSet</returns>
        public DataSet GetProducts(){
            var adapter = new productTableAdapter();
            DataSet result = new DataSet();
            try{
                result = tableToSet(adapter.GetProducts());
            }
            finally { adapter.Connection.Close(); }
            return result;
        }

        /// <summary>
        /// Gets a smaller version of the productTable in database
        /// </summary>
        /// <returns>DataSet: productId, name, productDescription, stockStatus, price</returns>
        public DataSet GetProductsSimple(){
            var adapter = new productTableAdapter();
            DataSet result = new DataSet();
            try
            {
                result = tableToSet(adapter.GetProductsSimple());
            }
            finally { adapter.Connection.Close(); }
            return result;
        }

        /// <summary>
        /// Update the OrderProduct table, and update the amount of target product
        /// </summary>
        public void UpdateStockStatus(int newAmount, int productId)
        {
            var adapter = new productTableAdapter();
            try
            {
                adapter.UpdateStockStatus(newAmount, productId);
            }
            finally { adapter.Connection.Close(); }
        }
        

        #region Order

        /// <summary>
        /// Inserts a new product to target order and the amount of the item
        /// </summary>
        /// <param name="orderId">Target order</param>
        /// <param name="productId">Target product</param>
        /// <param name="amount">How many items of target product</param>
        public void AddProductToOrder(int orderId, int productId, int amount)
        {
            var adapter = new orderProductTableAdapter();
            try { adapter.AddProductsToOrder(orderId, productId, amount); }
            finally { adapter.Connection.Close(); }
            
        }

        /// <summary>
        /// Get target order
        /// </summary>
        /// <param name="orderId">Target order (primary key)</param>
        /// <returns>DataSet that contains target order</returns>
        public DataSet GetOrder(int orderId)
        {
            var adapter = new orderProductTableAdapter();
            DataSet result = new DataSet();
            try
            {
                result = tableToSet(adapter.GetOrderById(orderId));
            }
            finally { adapter.Connection.Close(); }
            return result;
        }

        /// <summary>
        /// Get All orders
        /// </summary>
        /// <returns>DataSet that contains all orders</returns>
        public DataSet GetOrders()
        {
            var adapter = new orderUserTableAdapter();
            DataSet result = new DataSet();
            try
            {
                result = tableToSet(adapter.GetData());
            }
            finally { adapter.Connection.Close(); }
            return result;
        }

        /// <summary>
        /// Insert new order, owned by target user
        /// </summary>
        /// <param name="userId">userID from ASP.Net local database</param>
        /// <param name="date">The date and time the order is createad</param>
        public void AddOrder(string userId, DateTime date)
        {
            var adapter = new orderUserTableAdapter();
            try { adapter.AddOrder(userId, date); }
            finally { adapter.Connection.Close(); }
        }

        /// <summary>
        /// Get all orders from target user, sorted: last order first
        /// </summary>
        /// <param name="userId">userID from ASP.Net local database</param>
        /// <returns></returns>
        public DataSet GetOrdersByUser(string userId)
        {
            var adapter = new orderUserTableAdapter();
            DataSet result = new DataSet();
            try
            {
                result = tableToSet(adapter.GetOrdersByUser(userId));
            }
            finally { adapter.Connection.Close(); }
            return result;
        }

        #endregion


        /// <summary>
        /// Get all products in database that contains prefixText. Main use is to get easy access to fill
        /// menus, inputs etc. 
        /// </summary>
        /// <example>
        /// AJAX: AutoComplete result in product search
        /// </example>
        /// <param name="prefixText">Part of product name</param>
        /// <returns>Array of product names that contains prefixText</returns>
        public string[] GetCompletionList(string prefixText) {
            fn_searchTableAdapter adapter = new fn_searchTableAdapter();
            List<String> result = new List<string>();
            try
            {
                foreach (DataRow row in adapter.GetData(prefixText))
                {
                    result.Add(row["name"].ToString());
                }
            }
            finally {
                adapter.Connection.Close();
            }
            return result.ToArray();
        }

        /// <summary>
        /// Inserts the results from the adapters to DataSet. DataSet is easyer to consume 
        /// through the Service Reference. It also makes the code smaller on the ASP.NET side 
        /// because you can bind the Results directly to a DataSource
        /// </summary>
        /// <param name="dt">Result from tableAdapater</param>
        /// <returns>adapter result in a DataSet</returns>
        private DataSet tableToSet(DataTable dt)
        {
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            return ds;
        }
    }
}
